﻿@using Radzen
@using Radzen.Blazor.Rendering

@typeparam TValue
@inherits RadzenComponent
@implements IRadzenFormComponent
@if (Visible)
{
    <div @ref="@Element" @attributes="Attributes" class="@GetCssClass()" style="@GetStyle()" id="@GetId()">
        @if (!Inline)
        {
            @if (ShowInput || !ShowButton)
            {
                <input @ref="@input" @attributes="InputAttributes" disabled="@Disabled" readonly="@IsReadonly" value="@FormattedValue" tabindex="@(Disabled ? "-1" : $"{TabIndex}")"
                        @onchange="@ParseDate" autocomplete="off" type="text" name="@Name" @onkeydown="@(args => OnKeyPress(args))" @onkeydown:preventDefault=preventKeyPress @onkeydown:stopPropagation
                       class="rz-inputtext @InputClass @(ReadOnly ? "rz-readonly" : "") @(!ShowButton ? "rz-input-trigger" : "")" id="@Name" placeholder="@CurrentPlaceholder" />
            }
            @if (ShowButton)
            {
                <button aria-label="@ToggleAriaLabel" @onmousedown=@OnToggle class="@($"rz-datepicker-trigger{(ShowInput ? " rz-datepicker-field-button" : "")} rz-button rz-button-icon-only{(Disabled ? " rz-state-disabled" : "")} {ButtonClass}")" tabindex="-1" type="button">
                    <span aria-hidden="true" class="@ButtonClasses"></span><span class="rz-button-text"></span>
                </button>
            }
            @if (AllowClear && HasValue && (ShowInput || !ShowButton))
            {
                <i class="notranslate rz-dropdown-clear-icon rzi rzi-times" @onclick="@Clear" @onclick:stopPropagation="true"></i>
            }
        }

        <Popup id="@PopupID" Lazy=@(PopupRenderMode == PopupRenderMode.OnDemand) @ref=@popup style=@PopupStyle class="@($"{(Inline ? "rz-datepicker-inline-container " : "rz-datepicker-popup-container ")}")">
                <div class="rz-calendar" @onkeydown="@OnPopupKeyDown">
                    @if (!TimeOnly)
                    {
                        <div class="rz-calendar-header">
                            <a id="@(GetId() + "pm")" tabindex="-1" aria-label="@PrevMonthAriaLabel" @onclick:preventDefault="true" class="rz-button rz-button-md rz-variant-text rz-button-icon-only rz-secondary rz-shade-default rz-calendar-prev" @onclick="@(() => { if (!Disabled) { try { if(CurrentDate.AddMonths(-1).Year >= YearFrom) {CurrentDate = CurrentDate.AddMonths(-1);}} catch (ArgumentOutOfRangeException) {}} })">
                                <span class="notranslate rzi rz-calendar-prev-icon"></span>
                            </a>
                            <a id="@(GetId() + "nm")" tabindex="-1" aria-label="@NextMonthAriaLabel" @onclick:preventDefault="true" class="rz-button rz-button-md rz-variant-text rz-button-icon-only rz-secondary rz-shade-default rz-calendar-next" @onclick="@(() => { if (!Disabled) { try { if(CurrentDate.AddMonths(1).Year <= YearTo) {CurrentDate = CurrentDate.AddMonths(1);}} catch (ArgumentOutOfRangeException) {} } })">
                                <span class="notranslate rzi rz-calendar-next-icon"></span>
                            </a>
                            <div class="rz-calendar-title">
                                <RadzenDropDown @ref="monthDropDown" class="rz-calendar-month-dropdown" TabIndex="@TabIndex"
                                                TValue="int" Value="@CurrentDate.Month" Disabled="@Disabled" Data="@months" TextProperty="Name" ValueProperty="Value"
                                                Change="@((args) => { SetMonth(int.Parse(args.ToString())); })"/>
                                <RadzenDropDown @ref="yearDropDown" class="rz-calendar-year-dropdown" TabIndex="@TabIndex"
                                                TValue="int" Value="@CurrentDate.Year" Disabled="@Disabled" Data="@years" TextProperty="Name" ValueProperty="Value"
                                                Change="@((args) => { SetYear(int.Parse(args.ToString())); })" />
                            </div>
                        </div>
                        @if(ShowDays)
                        {
                        <div class="rz-calendar-view-container" tabindex="@(Disabled ? "-1" : $"{TabIndex}")" @onkeydown="@(args => OnCalendarKeyPress(args))" @onkeydown:preventDefault=preventKeyPress @onkeydown:stopPropagation>
                            <table class="rz-calendar-view rz-calendar-month-view" style="@(Inline ? "" : "width:100%")">
                                <thead>
                                    <tr>
                                        @if (ShowCalendarWeek)
                                        {
                                            <th scope="col" class="rz-datepicker-week-number">
                                                <span>@CalendarWeekTitle</span>
                                            </th>
                                        }
                                        @foreach (var day in ShiftedAbbreviatedDayNames)
                                        {
                                            <th scope="col">
                                                <span>@day</span>
                                            </th>
                                        }
                                    </tr>
                                </thead>
                                <tbody>
                                    @{
                                        int dayNumber = 0;
                                    }
                                    @for (int i = 0; i < 6; i++)
                                    {
                                        <tr>
                                            @if (ShowCalendarWeek)
                                            {
                                                <td class="rz-calendar-other-month rz-calendar-week-number">@Culture.Calendar.GetWeekOfYear(new DateTime(CurrentDate.Year, CurrentDate.Month, 1).AddDays(i * 7), Culture.DateTimeFormat.CalendarWeekRule, Culture.DateTimeFormat.FirstDayOfWeek)</td>
                                            }
                                            @for (int j = 0; j < 7; j++)
                                            {
                                                @if((DateTime.MaxValue - StartDate).TotalDays <= dayNumber)
                                                {
                                                    break;
                                                }

                                                DateTime date = StartDate.AddDays(dayNumber++);
                                                var dateArgs = DateAttributes(date);

                                                <td @attributes="@(dateArgs.Attributes)" class="@GetDayCssClass(date, dateArgs)" 
                                                @onclick="@(async () => { if (!Disabled && !dateArgs.Disabled) { await SetDay(date); } })">
                                                    <span class=@GetDayCssClass(date, dateArgs, false)>@date.Day</span>
                                                </td>
                                            }
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                        }
                        @if (FooterTemplate != null)
                        {
                            <div class="rz-datepicker-footer">
                                 @FooterTemplate
                            </div>
                        }
                    }
                </div>
                @if (ShowTime)
                {
                <div class="rz-timepicker" @onmousedown:stopPropagation>
                        @if (ShowHour)
                        {
                        <RadzenNumeric InputAttributes="@(new Dictionary<string,object>(){ { "aria-label", "hour" }})" TValue="int" Disabled="@Disabled" Value="@(HourFormat == "12" ? ((CurrentDate.Hour + 11) % 12) + 1 : CurrentDate.Hour)"
                           Min="@(HourFormat == "12" ? 1 : -1)" Max="@(HourFormat == "12" ? 12 : 24)" Step="@HoursStep"
                           Change="@UpdateHour" class="rz-hour-picker" @oninput=@OnUpdateHourInput Format="@(PadHours ? "00" : "")" Name="@($"{UniqueID}-h")" />
                        }
                        @if (ShowMinutes)
                        {
                        <div class="rz-separator">
                            <span>:</span>
                        </div>
                        <RadzenNumeric InputAttributes="@(new Dictionary<string,object>(){ { "aria-label", "minutes" }})" TValue="int" Disabled="@Disabled" Value="CurrentDate.Minute" Step="@MinutesStep" Min="0" Max="59"
                           Change="@UpdateMinutes" class="rz-minute-picker" @oninput=@OnUpdateHourMinutes Format="@(PadMinutes ? "00" : "")" Name="@($"{UniqueID}-m")"/>
                        }
                        @if (ShowSeconds)
                        {
                            <div class="rz-separator">
                                <span>:</span>
                            </div>
                            <RadzenNumeric InputAttributes="@(new Dictionary<string,object>(){ { "aria-label", "seconds" }})" TValue="int" Disabled="@Disabled" Value="CurrentDate.Second" Step="@SecondsStep" Min="0" Max="59"
                               Change="@UpdateSeconds" class="rz-second-picker" @oninput=@OnUpdateHourSeconds Format="@(PadSeconds ? "00" : "")" Name="@($"{UniqueID}-s")"/>
                        }
                        @if (HourFormat == "12")
                        {
                            <div class="rz-ampm-picker">
                                <a id="@(GetId() + "ampmup")" tabindex="@(Disabled ? "-1" : $"{TabIndex}")" aria-label="@ToggleAmPmAriaLabel" @onclick:preventDefault="true" @onclick="@ToggleAmPm">
                                    <span class="notranslate rzi rzi-chevron-up"></span>
                                </a>
                                <span>@CurrentDate.ToString("tt")</span>
                                <a id="@(GetId() + "ampmdown")" tabindex="@(Disabled ? "-1" : $"{TabIndex}")" aria-label="@ToggleAmPmAriaLabel" @onclick:preventDefault="true" @onclick="@ToggleAmPm">
                                    <span class="notranslate rzi rzi-chevron-down"></span>
                                </a>
                            </div>
                        }
                        @if (ShowTimeOkButton)
                        {
                            <button aria-label="@OkAriaLabel" type="button" class="rz-button rz-button-md rz-secondary" tabindex="0" @onclick="@(args => OkClick())">
                                <span class="rz-button-text">@OkAriaLabel</span>
                            </button>
                        }
                    </div>
                }
        </Popup>

    </div>
}
